package com.miniapp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.miniapp.design.aop.ApiAccessLog;
import com.miniapp.design.aop.RequiresRoles;
import com.miniapp.entity.R;
import com.miniapp.entity.User;
import com.miniapp.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author author
 * @date 2025-09-01 10:02
 */
@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户列表
     */
    @GetMapping
    @RequiresRoles("admin")
    @ApiAccessLog(operateModule = "用户管理", operateName = "分页查询用户列表")
    public R<List<User>> getUserList(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            User user) {
        Page<User> page = new Page<>(current, size);
        IPage<User> userPage = userService.page(page);
        return R.success(userPage.getRecords(), userPage.getTotal(), current, size);
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public R<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return R.error(404, "用户不存在");
        }
        return R.success(user);
    }

    /**
     * 创建新用户
     */
    @PostMapping
    public R<User> createUser(@RequestBody User user) {
        boolean saved = userService.save(user);
        if (saved) {
            return R.success(user);
        }
        return R.error("创建用户失败");
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public R<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        boolean updated = userService.updateById(user);
        if (updated) {
            return R.success(userService.getById(id));
        }
        return R.error("更新用户失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteUser(@PathVariable Long id) {
        boolean deleted = userService.removeById(id);
        if (deleted) {
            return R.success();
        }
        return R.error("删除用户失败");
    }
}